package cn.wolfcode.trip.base.admin.controller;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.query.StrategyCatalogQueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

@Controller
@RequestMapping("strategyDetail")
public class StrategyDetailController {

    @Autowired
    private IStrategyDetailService strategyDetailService;

    @Autowired
    private ServletContext servletContext;

    @RequestMapping("list")
    public String list(Model model, @ModelAttribute("qo") StrategyCatalogQueryObject qo){
        model.addAttribute("result", strategyDetailService.query(qo));
        return "strategy/detail";
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(MultipartFile file, StrategyDetail strategyDetail){

        JSONResult result = new JSONResult();

        try {

            if(file!=null&&file.getSize() > 0){
                String imgUrl = UploadUtil.upload(file, servletContext.getRealPath("/upload"));
                strategyDetail.setCoverUrl(imgUrl);
            }

            if(strategyDetail.getId() != null){
                strategyDetailService.update(strategyDetail);
            }else{
                strategyDetailService.save(strategyDetail);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @RequestMapping("getContenById")
    @ResponseBody

    public StrategyContent getContenById (Long id){
        return strategyDetailService.getContenById(id);
    }



}
